package io.grpc.examples.helloworld.Service.impl;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.HelloServiceGrpc;
import io.grpc.examples.helloworld.HelloServiceProto;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {

    private final int port = 9999;
    private Server server;


    /**
     * 重写下方法。
     * @param request
     * @param responseObserver
     */
    @Override
    public void sayHello(HelloServiceProto.HelloRequest request, StreamObserver<HelloServiceProto.HelloResponse> responseObserver) {
        System.out.println("收到sayHello请求");
        //request 处理
        String name = request.getName();
        System.out.println(name);
        //response处理
        HelloServiceProto.HelloResponse build = HelloServiceProto.HelloResponse.newBuilder()
                .setMessage("nametest"+name)
                .build();
        responseObserver.onNext(build);
        responseObserver.onCompleted();
    }


    //这里抄的。没空研究。
    public void start() throws IOException {
        server = ServerBuilder.forPort(port)
                //HelloServiceImpl 就是当前类
                .addService(new HelloServiceImpl())
                .build()
                .start();
        System.out.println("service start...at port" + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                HelloServiceImpl.this.stop();
                System.out.println("程序出错或正常退出！");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * 不让main线程断开
     *
     * @throws InterruptedException
     */
    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
